import 'package:mqtt_client/mqtt_server_client.dart';
import 'package:mqtt_client/mqtt_client.dart';

class mqtt{

  late dynamic status;

  MqttServerClient client =
  MqttServerClient.withPort('192.168.100.230', '001', 1883);


  //消息监听
  Future<dynamic> Message(zt, xx) async {
    var pt;
      //订阅主题
    await this.client.subscribe("rf/#", MqttQos.atLeastOnce);

    //消息发布
    // const pubTopic = 'chenhaiwei'; //发布消息的主题
    final builder = MqttClientPayloadBuilder();
    builder.addString(xx); //发布的内容
    await client.publishMessage(zt, MqttQos.atLeastOnce, builder.payload);

    //取消订阅
    client.onUnsubscribed(zt);

    //监听消息
    client.updates!.listen((List<MqttReceivedMessage<MqttMessage?>>? c) {
      var recMess = c![0].payload as MqttPublishMessage;
      pt = MqttPublishPayload.bytesToStringAsString(recMess.payload.message!);
      // log('消息:$pt,主题: <${c[0].topic}>');
    });
    return pt;
  }

  //页面销毁时关闭连接
  @override
  void dispose() {
    client.onDisconnected(); //断开连接
  }
  void cc(){
    //设置mqtt参连接相关参数
    client.onConnected = onConnected; //连接成功回调
    client.onDisconnected = onDisconnected; //连接断开回调
    client.onSubscribed = onSubscribed; //订阅成功回调
    client.onSubscribeFail = onSubscribeFail; //订阅失败回调
    client.onUnsubscribed = onUnsubscribed; //取消订阅回调
    client.pongCallback = pong; //收到 PING 响应回调
    client.logging(on: false); //设置是否登陆
    client.connect();
  }
  void onConnected() {
    print('连接成功');
  }

// 连接断开
  void onDisconnected() {
    print('连接断开');
  }

// 订阅主题成功
  void onSubscribed(String topic) {
    print('订阅主题$topic成功');
  }

// 订阅主题失败
  void onSubscribeFail(String topic) {
    print('订阅主题 $topic失败');
  }

// 成功取消订阅
  void onUnsubscribed(String topic) {
    print('成功取消$topic主题订阅');
  }

// 收到 PING 响应
  void pong() {
    print('收到 PING 响应');
  }

}
